package com.codedef.cidaren.controller;

import com.codedef.cidaren.common.exception.CustomException;
import com.codedef.cidaren.common.response.Result;
import com.codedef.cidaren.common.response.ResultCode;
import com.codedef.cidaren.constants.JwtConstant;
import com.codedef.cidaren.controller.base.BaseController;
import com.codedef.cidaren.entity.CdkeyEntity;
import com.codedef.cidaren.entity.UserEntity;
import com.codedef.cidaren.service.CdkeyService;
import com.codedef.cidaren.util.IpUtil;
import com.codedef.cidaren.util.JwtUtils;
import com.codedef.cidaren.util.RedisUtil;
import com.codedef.cidaren.valid.UpdateGroup;
import com.codedef.cidaren.vo.CdkeyVo;
import com.ramostear.captcha.HappyCaptcha;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/cdkey")
public class CdkeyController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    CdkeyService cdkeyService;

    @RequestMapping(path = "/conversion", method = {RequestMethod.GET, RequestMethod.POST})
    public Result conversionCdkey(@RequestHeader(JwtConstant.AUTH_HEADER_KEY) String authorization,
                                  @RequestBody @Validated(UpdateGroup.class) CdkeyVo cdkeyVo,
                                  HttpServletRequest request) {

        // 验证验证码
        //Verification Captcha
        boolean flag = HappyCaptcha.verification(request, cdkeyVo.getCaptcha(), true);
        if (!flag) {  // 验证码错误
            // 删除Session的的验证码
            HappyCaptcha.remove(request);
            // 抛出异常
            throw new CustomException(ResultCode.CAPTCHA_ERROR);
        }

        // 删除Session的的验证码
        HappyCaptcha.remove(request);

        String cdkey = cdkeyVo.getCdkey();
        String ipAddr = IpUtil.getIpAddr(request);
        // 兑换
        Map<String, Object> resultMap = cdkeyService.conversionCdkey(authorization, cdkey, ipAddr);

        return new Result(ResultCode.SUCCESS, resultMap);
    }

}
